<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="500px" :title="`${drawerProps.title}`">
    <el-form
      ref="deviceKindFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="设备分类名称" prop="kindName">
        <el-input v-model="drawerProps.row!.kindName" placeholder="请填写设备分类名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="drawerProps.row!.remark" :rows="2" type="textarea" placeholder="请填写备注" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="DeviceKindDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { DeviceKind } from "@/api/interface";

const rules = reactive({
  kindName: [{ required: true, message: "请填写设备分类名称" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<DeviceKind.ResDeviceKindList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const deviceKindFormRef = ref<FormInstance>();
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  deviceKindFormRef.value && deviceKindFormRef.value.resetFields();
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  deviceKindFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!({ ...drawerProps.value.row });
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
defineExpose({
  acceptParams
});
</script>
